package org.gp953.product.controller;

import org.gp953.basic.util.AjaxResult;
import org.gp953.basic.util.PageList;
import org.gp953.product.domain.Product;
import org.gp953.product.domain.ProductDetail;
import org.gp953.product.query.ProductQuery;
import org.gp953.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 高级查询加分页
     * @param query
     * @param request
     * @return
     */
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query, HttpServletRequest request){
        return productService.queryPageData(query);
    }

    /**
     * 上架服务
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            productService.onSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }

    /**
     * 下架服务
     * @param ids
     * @return
     */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            productService.offSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }

    @PutMapping
    public AjaxResult addAndUpdate(@RequestBody Product product){
        try {
            if (product != null &&  product.getId()!=null){
                productService.update(product);
            }else {
                productService.add(product);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败！！");
        }
    }

    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id){
        return productService.queryById(id);
    }

    /**
     *  通过id删除
     * @return
     * 定义接口的三要素：
     * 1.请求地址
     * 2.请求参数
     * 3.返回值
     */
    @DeleteMapping("/{id}")// {id}是占位符，@PathVariable表示从url的中拿值
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            productService.delete(id);

            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作失败").setSuccess(false);
        }
    }
}
